package com.thinkfit.jy.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.common.lib.constant.EventBusEvent;
import com.common.lib.fragment.BaseFragment;
import com.common.lib.mvp.contract.EmptyContract;
import com.common.lib.mvp.presenter.EmptyPresenter;
import com.thinkfit.jy.R;
import com.thinkfit.jy.adapter.PeerAdapter;
import com.thinkfit.jy.utils.OnMirrorListener;
import com.thinkfit.jy.utils.WiFiDirectMgr;

import java.util.Collection;
import java.util.HashMap;

public class PeerListFragment extends BaseFragment<EmptyContract.Presenter> implements EmptyContract.View {

    PeerAdapter peerAdapter;

    boolean isConnect = false;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_peer_list;
    }

    @Override
    protected void initView(@NonNull View view, @Nullable Bundle savedInstanceState) {
        setViewsOnClickListener(R.id.tvBack, R.id.tvSearch);

        WiFiDirectMgr instance = WiFiDirectMgr.getInstance();
        instance.setOnMirrorListener(getOnMirrorListener());
        instance.start(getContext());

        RecyclerView recyclerView = view.findViewById(R.id.rvSearchedDevice);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        getPeerAdapter().onAttachedToRecyclerView(recyclerView);
        recyclerView.setAdapter(getPeerAdapter());

    }

    @Override
    public void onReceive(@NonNull HashMap<String, Object> map) {
        super.onReceive(map);
        if (map.containsKey(EventBusEvent.REFRESH_PEER)) {
            WifiP2pDeviceList wifiP2pDeviceList = (WifiP2pDeviceList) map.get(EventBusEvent.REFRESH_PEER);
            Collection<WifiP2pDevice> deviceList = wifiP2pDeviceList.getDeviceList();
            getPeerAdapter().setList(deviceList);
            getPeerAdapter().notifyDataSetChanged();
        }
    }

    private PeerAdapter getPeerAdapter() {
        if (peerAdapter == null) {
            peerAdapter = new PeerAdapter(getContext());
            peerAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                    if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.NEARBY_WIFI_DEVICES) != PackageManager.PERMISSION_GRANTED) {
                        // TODO: Consider calling
                        //    ActivityCompat#requestPermissions
                        // here to request the missing permissions, and then overriding
                        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                        //                                          int[] grantResults)
                        // to handle the case where the user grants the permission. See the documentation
                        // for ActivityCompat#requestPermissions for more details.
                        return;
                    }
                    WiFiDirectMgr.getInstance().stop();
                    WifiP2pManager wifiP2pManager = WiFiDirectMgr.getInstance().getWifiP2pManager();
                    WifiP2pDevice item = peerAdapter.getItem(position);
                    WifiP2pConfig wifiP2pConfig = new WifiP2pConfig();
                    wifiP2pConfig.deviceAddress = item.deviceAddress;
                    wifiP2pConfig.groupOwnerIntent = WifiP2pConfig.GROUP_OWNER_INTENT_MIN;
                    if(!isConnect){
                        isConnect = true;
                        wifiP2pManager.connect(WiFiDirectMgr.getInstance().getChannl(),wifiP2pConfig, new WifiP2pManager.ActionListener() {
                            @Override
                            public void onSuccess() {
                                System.out.println("MiraWiFiDirectMgr -------------->   onSuccess ");

                            }

                            @Override
                            public void onFailure(int i) {
                                System.out.println("MiraWiFiDirectMgr -------------->   onFailure : "+i);
                                cancelConnect(wifiP2pManager);
                            }
                        });
                    }else {
                        isConnect = false;
                        cancelConnect(wifiP2pManager);
                    }

                }
            });
        }

        return peerAdapter;
    }

    /**
     * 断开设备连接
     * @param wifiP2pManager
     */
    public void cancelConnect(WifiP2pManager wifiP2pManager){
        wifiP2pManager.cancelConnect(WiFiDirectMgr.getInstance().getChannl(), new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                System.out.println("MiraWiFiDirectMgr -------------->cancelConnect    onSuccess ");
            }

            @Override
            public void onFailure(int i) {
                System.out.println("MiraWiFiDirectMgr -------------->cancelConnect    onFailure ");
            }
        });
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tvBack:
                getParentFragmentManager().popBackStack();
                break;
            case R.id.tvSearch:
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        WiFiDirectMgr.getInstance().stop();
    }

    public OnMirrorListener getOnMirrorListener(){
        OnMirrorListener onMirrorListener = new OnMirrorListener() {
            @Override
            public void onSessionBegin() {
                System.out.println("ddddddddddddddddddddddd  " + WiFiDirectMgr.TAG + "onSessionBegin");
            }

            @Override
            public void onSessionEnd() {
                System.out.println("ddddddddddddddddddddddd  " + WiFiDirectMgr.TAG + "onSessionEnd");
            }

            @Override
            public void onMirrorStart() {
                System.out.println("ddddddddddddddddddddddd  " + WiFiDirectMgr.TAG + "onMirrorStart");
            }

            @Override
            public void onMirrorData(long seqNum, @Nullable byte[] data) {
                System.out.println("ddddddddddddddddddddddd  " + WiFiDirectMgr.TAG + "onMirrorData");
            }

            @Override
            public void onMirrorStop() {
                System.out.println("ddddddddddddddddddddddd  " + WiFiDirectMgr.TAG + "onMirrorStop");
            }
        };
        return onMirrorListener;
    }

    @NonNull
    @Override
    protected EmptyContract.Presenter onCreatePresenter() {
        return new EmptyPresenter(this);
    }
}
